package com.paireach.bw.utils;

/**
 * 字符串通用处理类
 *
 * @author luckystar
 */
public class CommonString {
    /**
     * <p>将byte数组转化为大写的十六进制字符串</br>例如：
     * <p> byte[] a = new byte[]{<b>(byte) 0x01</b>,<b>(byte) 0x7e</b>,<b>(byte) 0xaa</b>};
     * </br> 那么转化的结果为 <b>017EAA</b>
     *
     * @param b 待转化的byte数组
     * @return 大写的十六进制字符串
     */
    public static String byte2HexStr(byte[] b) {
        StringBuilder sb = new StringBuilder();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF)).toUpperCase();
            if (stmp.length() == 1)
                sb.append("0" + stmp);
            else
                sb.append(stmp);
        }
        return sb.toString().toUpperCase();
    }

    /**
     * <p>指定一个十六进制字符串，将其转换为byte数组
     * </br>如果字符串总长是奇数，则该字符串的最后一个字符将被忽略
     *
     * @param src 源字符串
     * @return 返回一个转换好的byte数组
     * @throws NumberFormatException 如果字符串中包含非十六进制字符（0~9,a~f,A~F）
     */
    public static byte[] hexStr2Bytes(String src) throws NumberFormatException {
        int m = 0, n = 0;
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = uniteBytes(src.substring(i * 2, m), src.substring(m, n));
        }
        return ret;
    }

    private static byte uniteBytes(String src0, String src1) throws NumberFormatException {
        byte b0 = Byte.decode("0x" + src0).byteValue();
        b0 = (byte) (b0 << 4);
        byte b1 = Byte.decode("0x" + src1).byteValue();
        byte ret = (byte) (b0 | b1);
        return ret;
    }

    /**
     * 将byte转化为字符串型
     *
     * @param b
     * @return
     */
    public static String getBinaryStrFromByte(byte b) {
        String result = "";
        byte a = b;
        for (int i = 0; i < 8; i++) {
            byte c = a;
            a = (byte) (a >> 1);
            a = (byte) (a << 1);
            if (a == c) {
                result = "0" + result;
            } else {
                result = "1" + result;
            }
            a = (byte) (a >> 1);
        }
        return result;
    }
}